package com.antilia.infomaresme.data.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.antilia.infomaresme.data.dao.interfaces.IItemsDao;
import com.antilia.infomaresme.data.dataobjects.Category;
import com.antilia.infomaresme.data.dataobjects.Item;
import com.antilia.infomaresme.data.dataobjects.VisibilityStatus;
import com.antilia.infomaresme.data.dataobjects.User;
/**
 * @author Ernesto
 *
 */
public class ItemsDaoHibernateImp extends AbstractDaoHibernateImpl<Item> implements IItemsDao{

	public ItemsDaoHibernateImp()
	{
		super(Item.class);
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Item> getItems(User user, Category category, Category place, int start, int size, Boolean priceAscending, Boolean rateAscending, VisibilityStatus status) {
		Criteria criteria = getSession().get().createCriteria(Item.class);
		criteria.setFetchSize(size);
		criteria.setFirstResult(start);
		configureCriteria(criteria, user, category, place, status);		
		if(priceAscending != null)
			if( priceAscending == true)
				criteria.addOrder(Order.asc("price"));
			else 
				criteria.addOrder(Order.desc("price"));
			
		if(rateAscending != null)
			if(rateAscending == true)
				criteria.addOrder(Order.asc("rating"));
			else 
				criteria.addOrder(Order.desc("rating"));
		return (List<Item>)criteria.list();
	}
	 
	public Long countItems(User user, Category category, Category place,  VisibilityStatus status) {
		Criteria criteria = session.get().createCriteria(Item.class);
		criteria.setProjection(Projections.rowCount());
		configureCriteria(criteria, user, category, place, status);
		return (Long)(criteria.uniqueResult());
	}
	
	private void configureCriteria(Criteria criteria, User user, Category category, Category place, VisibilityStatus status) {
		if(user != null) {
			criteria.add(Restrictions.eq("author", user));
		}
		if(status != null) {
			criteria.add(Restrictions.eq("status", status));
		}
		if(category != null) {
			String s = "%"+Item.buildCategory(category)+"%";
			System.out.println(s);
			criteria.add(Restrictions.like("categoryPath", s));
		}
		if(place != null) {
			String s = "%"+Item.buildCategory(place)+"%";
			System.out.println(s);
			criteria.add(Restrictions.like("geographicPath", s));
		}
	}
}
